<script setup>
import payService from '@/api/modules/pay/pay'
import SafeTopContainer from '@/components/SafeTopContainer/SafeTopContainer.vue'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const balance = computed(() => formatPrice(userStore.totalRechargeAmount || 0))
const bonusAmount = computed(() => formatPrice(userStore.bonusAmount || 0))

// 计算实际可提现金额
const availableAmount = computed(() => {
  const available = Math.max(0, (userStore.totalRechargeAmount || 0) - (userStore.bonusAmount || 0))
  console.log('可提现金额:', available)
  return formatPrice(available)
})

// 获取数值用于计算
const availableAmountValue = computed(() => Math.max(0, (userStore.totalRechargeAmount || 0) - (userStore.bonusAmount || 0)))
const toast = useToast()
const inputBalance = ref(0)

onShow(async () => {
  await userStore.getUserInfo()
})

function handleGetAll() {
  // 修复：设置为实际可提现金额
  inputBalance.value = availableAmountValue.value
}

async function handleWithdraw() {
  // 添加验证
  if (!inputBalance.value || inputBalance.value <= 0) {
    toast.error('请输入有效的提现金额')
    return
  }

  if (inputBalance.value > availableAmountValue.value) {
    toast.error('提现金额不能超过可提现余额')
    return
  }

  try {
    const { code } = await uni.login({ provider: 'weixin' })
    const params = {
      body: '提现',
      code,
      totalFeel: Number(inputBalance.value),
      withdrawType: 'withdraw1',
    }

    console.log('提现参数:', params)

    const res = await payService.withdraw(params)
    // uni.requestMerchantTransfer({
    //   mchId: '1631846088',
    //   package: '',
    //   success: (res) => {
    //     console.log('提现成功:', res)
    //   },
    //   fail: (res) => {
    //     console.error('提现失败:', res)
    //   },
    // })
    // toast.success('提现申请提交成功')
    //
    // // 提现成功后刷新用户信息
    // await userStore.getUserInfo()
    // // 清空输入框
    // inputBalance.value = 0
  }
  catch (err) {
    console.error('提现失败:', err)
    toast.error(err?.message || '提现失败，请稍后重试')
  }
}
</script>

<template>
  <safe-top-container :padding-bottom="15" bg-color="#fff" :show-bg-color="true">
    <wd-navbar left-arrow custom-class="!bg-transparent" title="提现" :bordered="false" @click-left="navigateBack" />
  </safe-top-container>
  <div class="mt-4 p-2">
    <div class="h-30 rounded bg-white p-4 shadow-sm">
      <div class="flex justify-between">
        <div class="text-base text-gray-800 font-medium">
          提现金额
        </div>
        <div
          class="text-base text-[#445DFF] font-medium"
          :class="{ 'opacity-50 cursor-not-allowed': availableAmountValue <= 0 }"
          @click="availableAmountValue > 0 && handleGetAll()"
        >
          全部
        </div>
      </div>
      <!--      <div class="mb-1 pt-5 text-center text-3xl text-gray-600 font-bold"> -->
      <!--        <span class="mr-3 text-xl">¥</span>{{ balance }} -->
      <!--      </div> -->
      <!--      <div class="mb-2 text-center text-gray-600 font-medium"> -->
      <!--        可提现余额 -->
      <!--      </div> -->
      <div class="mt-3">
        <wd-input
          v-model="inputBalance"
          type="digit"
          placeholder="请输入提现金额"
          prefix-icon="money-circle"
          :disabled="availableAmountValue <= 0"
          size="large"
          custom-class="withdraw-input"
        >
          <template #prefix>
            <div class="text-xl text-gray-800 font-medium">
              ¥
            </div>
          </template>
          <template #suffix>
            <div class="text-[12px] text-[#999999] font-medium">
              可提现金额 {{ availableAmount }}
            </div>
          </template>
        </wd-input>
      </div>
      <div class="mt-3 flex items-center text-[12px] text-[#999999]">
        <wd-icon name="warning" size="22px" class="mr-1" />
        不可提现金额：{{ bonusAmount }}
      </div>
    </div>
  </div>
  <div class="absolute bottom-10 w-full">
    <div class="mb-5 w-full flex justify-center text-[14px] text-[#999999]">
      <div>
        <p>提现说明：</p>
        <p>1、返佣提现会直接存到微信账号；</p>
        <p>2、发起返佣提现申请后在2小时内会成功提取相应金额</p>
        <p> 账户请留意账户明细；</p>
        <p>3、有问题前往我的-联系客服；</p>
      </div>
    </div>
    <div class="w-full flex justify-center">
      <wd-button
        type="primary" block size="large"
        :disabled="!inputBalance || inputBalance <= 0 || inputBalance > availableAmountValue || availableAmountValue <= 0 "
        custom-class="!w-[90%]"
        :rounder="formatAmount"
        @click="handleWithdraw"
      >
        提现
      </wd-button>
    </div>
  </div>
</template>

<style lang="scss">
.withdraw-card{
  height: 324rpx;
}
.withdraw-input{
  &.is-large{
  padding-bottom: 8px !important;
    .wd-input__inner {
      font-size: 20px !important;
    }
  }
}
</style>
